#define DBC_CHECK_PRECONDITION

using System;
using System.Xml;

using DesignByContract;

namespace Outcoding.GraphGenerator.Entities.XmlBuilders {
    public class IAxisValueXmlBuilder : IXmlBuilder {

        private XmlTagNames mTag = XmlTagNames.unknown;

        private IAxisValue mResultObject = null;

        public IAxisValue ResultObject {
            get {
                return mResultObject;
            }
        }

        public IAxisValueXmlBuilder(XmlNode iAxisValueXmlNode) {
            Check.Require(iAxisValueXmlNode != null, "Xml source node cannot be null");
            mTag = this.TagSelector(iAxisValueXmlNode);
            Check.Require(mTag != XmlTagNames.unknown, "A MinValue, MaxValue or Scale node must be supplied.");
            this.BuildObject(iAxisValueXmlNode);
        }

        private void BuildObject(XmlNode iAxisValueXmlNode) {
            switch(mTag){
                case XmlTagNames.minvalue:
                    mResultObject = new MinValue();
                    break;
                case XmlTagNames.maxvalue:
                    mResultObject = new MaxValue();
                    break;
                case XmlTagNames.scale:
                    mResultObject = new Scale();
                    break;
            }

            try {
                if (iAxisValueXmlNode.Attributes["enabled"] != null)
                    mResultObject.IsEnabled = ParseIsEnableAttribute(iAxisValueXmlNode);
                mResultObject.Value = this.ParseValue(iAxisValueXmlNode);
            } catch (DesignByContract.PreconditionException preExc) {
                //log error
                mResultObject = null;
                throw;
            }
        }

        private bool ParseIsEnableAttribute(XmlNode iAxisValueXmlNode) {
            Check.Require(iAxisValueXmlNode.Attributes["enabled"] != null, "enabled attribute not present");
            return Boolean.Parse(iAxisValueXmlNode.Attributes["enabled"].Value);
        }

        private double ParseValue(XmlNode iAxisValueXmlNode) {
            return Double.Parse(iAxisValueXmlNode.InnerText.Trim());
        }

        private XmlTagNames TagSelector(XmlNode iAxisValueXmlNode) {
            XmlTagNames tag = XmlTagNames.unknown;
            switch(iAxisValueXmlNode.Name){
                case "minvalue":
                    tag = XmlTagNames.minvalue;
                    break;
                case "maxvalue":
                    tag = XmlTagNames.maxvalue;
                    break;
                case "scale":
                    tag = XmlTagNames.scale;
                    break;
            }
            return tag;
        }
    }
}